package com.example.newproject_overseas.exception

import android.os.Handler
import android.os.Looper
import android.util.Log
import android.widget.Toast
import androidx.navigation.NavHostController
import com.example.newproject_overseas.MyApplication
import retrofit2.HttpException

class NetworkExceptionHandler {

    companion object {

        private val mainHandler = Handler(Looper.getMainLooper())
        fun handleException(e: Exception,navController: NavHostController) {
            if (e is HttpException) {
                handleHttpException(e,navController)
            } else {
                handleOtherException(e,navController)
            }
        }

        private fun handleHttpException(e: HttpException,navController: NavHostController) {
            val errorCode = e.code()
            val errorMessage = e.message()
            when (errorCode) {
                // 根据具体的 HTTP 错误码进行处理
                503  -> showErrorMessage("Service unavailable")
                1012 -> navController.navigate("login")
                // 处理其他错误码...
                else -> showErrorMessage("An error occurred: $errorCode - $errorMessage")
            }
        }

        private fun handleOtherException(e: Exception,navController: NavHostController) {
            showErrorMessage("An error occurred: ${e.message}")
        }



        private fun showErrorMessage(message: String) {
            // 在这里实现显示错误消息的逻辑，可以使用 Toast 或者其他方式
            Log.e("NetworkExceptionHandler", message)

            mainHandler.post {
                Toast.makeText(
                    MyApplication.appContext,"No internet connection. Please check your network settings.",
                    Toast.LENGTH_SHORT).show()
            }
        }
    }
}
